package com.interactive.internal.ant;

import java.io.File;
import java.util.Calendar;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class InjectTimeBomb extends Task
{
  public void execute() throws BuildException
  {
    validateAttributes();

    System.out.println("Attempting to inject timebomb into " + javaFileName +
                       "...");

    StringBuffer timebombCode = InjectionUtils.readResourceFile("timebomb.txt");

    Calendar current = Calendar.getInstance();
    current.add(Calendar.DAY_OF_MONTH, trialDays);

    int year = current.get(java.util.Calendar.YEAR);
    InjectionUtils.replaceAll(timebombCode, "EXPIRE_YEAR",
                              Integer.toString(year));

    int month = current.get(java.util.Calendar.MONTH) + 1;
    InjectionUtils.replaceAll(timebombCode, "EXPIRE_MONTH",
                              Integer.toString(month));

    int day = current.get(java.util.Calendar.DAY_OF_MONTH);
    InjectionUtils.replaceAll(timebombCode, "EXPIRE_DAY", Integer.toString(day));

    if (productName != null)
      InjectionUtils.replaceAll(timebombCode, "INT_PRODUCT",
                                "\"" + productName + "\"");

    StringBuffer javaCodeToBeInjected = InjectionUtils.readFile(javaFileName);

    InjectionUtils.replaceLine(javaCodeToBeInjected, "@PRODUCT_INIT_TAG@",
                               timebombCode.toString(), true);

    InjectionUtils.writeFile(javaFileName, javaCodeToBeInjected.toString());

    System.out.println("Successfully injected timebomb code.");
  }

  // Attribute Access for ANT
  public void setJavaFile(File javaFile)
  {
    javaFileName = javaFile.getAbsolutePath();
  }

  private String javaFileName = null;

  public void setTrialDays(int trialDays)
  {
    this.trialDays = trialDays;
  }

  private int trialDays = Integer.MIN_VALUE;

  public void setProductName(String productName)
  {
    this.productName = productName;
  }

  private String productName = null;

  private void validateAttributes()
      throws BuildException
  {
    if (javaFileName == null)
      throw new BuildException("Java File is required.");
    if (trialDays < 0)
    {
      if (trialDays == Integer.MIN_VALUE)
      {
        trialDays = 30;
        System.out.println("Trial Days not specified: defaulting to " +
                           trialDays + " days.");
      }
      else
      {
        throw new BuildException(
            "Trial Days must be a positive non-zero value.");
      }
    }
  }
}
